package com.zhuliyou.ai.service;

import com.alibaba.fastjson.JSONObject;
import com.zhuliyou.ai.config.CustomConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 身份验证服务
 *
 * @author zhuliyou
 * @date 2021/06/02
 */
@Component
public class AuthService {

    @Autowired
    private CustomConfig customConfig;

    public String getAuth() {
        String clientId = customConfig.getClientId();
        String clientSecret = customConfig.getClientSecret();
        return getAuth(clientId, clientSecret);
    }

    public String getAuth(String ak, String sk) {
        String authHost = customConfig.getAuthHost();
        String getAccessTokenUrl = authHost
                + "grant_type=client_credentials"
                + "&client_id=" + ak
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            JSONObject jsonObject = JSONObject.parseObject(result.toString());
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return null;
    }

}